﻿using AutoMapper;
using Microsoft.Extensions.Logging;
using XsqTech.SmartOA.Domain.Table;
using XsqTech.SmartOA.Dtos.DTO;
using XsqTech.SmartOA.EFCore.Respository;
using XsqTech.SmartOA.IRespository;
using XsqTech.SmartOA.IService;
using XsqTech.SmartOA.Service.DTO;

namespace XsqTech.SmartOA.Service
{
    public class UserService : IUserService
    {
        readonly IUserRespository _baseUser;
        private readonly ILogger<UserService> _logger;
        readonly IMapper _mapper;
        readonly IUnitOfWork _unitOfWork;
        readonly IRolesRespository _baseRolers;
        readonly IRolePermissionRespository _baseRolePermission;
        readonly IUserRoleRespository _baseUserRole;

        public UserService(IUserRespository baseUser, ILogger<UserService> logger, IMapper mapper, IUnitOfWork unitOfWork, IRolesRespository baseRolers, IRolePermissionRespository baseRolePermission, IUserRoleRespository baseUserRole)
        {
            _baseUser = baseUser;
            _logger = logger;
            _mapper = mapper;
            _unitOfWork = unitOfWork;
            _baseRolers = baseRolers;
            _baseRolePermission = baseRolePermission;
            _baseUserRole = baseUserRole;
        }


        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public ResponseModel GetLogin(UserLogin dto)
        {
            try
            {
                var pass = MD5Hash.Hash.Content(dto.Password);
                if (string.IsNullOrEmpty(dto.Name))
                {
                    return new ResponseModel
                    {
                        Code = State.请求失败,
                        Message = "用户名不能为空",
                        Data = null
                    };
                }
                if (_baseUser.Query().Where(x => x.UserName == dto.Name).Count() > 1)
                {
                    return new ResponseModel
                    {
                        Code = State.请求失败,
                        Message = "用户名不能重复",
                        Data = null
                    };
                }
                if (string.IsNullOrEmpty(dto.Password))
                {
                    return new ResponseModel
                    {
                        Code = State.请求失败,
                        Message = "密码不能为空",
                        Data = null
                    };
                }
                var data = _baseUser.UserLogin(dto.Name, pass);
                if (data != null)
                {
                    return new ResponseModel
                    {
                        Code = State.请求成功,
                        Message = "登录成功",
                        Data = data
                    };
                }
                else
                {
                    return new ResponseModel
                    {
                        Code = State.请求失败,
                        Message = "登录失败",
                        Data = null
                    };
                }
            }
            catch (Exception ex)
            {
                //控制台输出
                Console.WriteLine(ex.Message);
                //写入日志
                _logger.LogError(ex.Message);
                throw;
            }
        }
        /// <summary>
        /// 用户添加
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        public ResponseModel UserAdd(AddUserDto m)
        {
            try
            {
                var list = _baseUser.Query().Where(x => x.UserName == m.UserName && x.UserPhone == m.UserPhone);
                if (list.Count() > 0)
                {
                    return new ResponseModel
                    {
                        Code = State.请求失败,
                        Message = "用户已从在",
                    };
                }
                m.UserPassword = MD5Hash.Hash.Content(m.UserPassword);
                var s = _mapper.Map<User>(m);
                _baseUser.Add(s);
                int data = _unitOfWork.SaveChangs();
                if (data > 0)
                {
                    return new ResponseModel
                    {
                        Code = State.请求成功,
                        Message = "添加成功",
                        Count = data,
                    };
                }
                else
                {
                    return new ResponseModel
                    {
                        Code = State.请求失败,
                        Message = "添加失败",
                        Count = data,
                    };
                }

            }
            catch (Exception ex)
            {
                //控制台输出
                Console.WriteLine(ex.Message);
                //写入日志
                _logger.LogError(ex.Message);
                throw;
                throw;
            };
        }
        /// <summary>
        /// 用户显示
        /// </summary>
        /// <param name="UserName"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public dynamic UserQuery(string UserName, int pageIndex, int pageSize)
        {
            var list = from x in _baseUser.Query()
                       select new UserDto
                       {
                           Id= x.Id,
                           UserName = x.UserName,
                           UserPhone = x.UserPhone,
                           UserMailbox = x.UserMailbox,
                           UserSex = x.UserSex,
                           State= x.State,
                           CreateTime = x.CreateTime,
                           HeadPortrait = x.HeadPortrait,
                           Roles = (List<string>)(from ur in _baseUserRole.Query()
                                             join r in _baseRolers.Query() on ur.RoleId equals r.RId
                                             where ur.UserId == x.Id
                                             select r.RName)
                       };
            
            if (!string.IsNullOrEmpty(UserName))
            {
                list = list.Where(x => x.UserName.Contains(UserName));
            }
            int Count = list.Count();
            var Plist = list.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();

            return new ResponseModel
            {
                Code = State.请求成功,
                Message = "查询成功",
                Data = Plist,
                Count = Count,
            };
        }
        /// <summary>
        /// 用户修改
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        public ResponseModel UserUpdate(AddUserDto m)
        {
            try
            {
                var s = _mapper.Map<User>(m);
                _baseUser.Update(s);
                int data = _unitOfWork.SaveChangs();
                if (data > 0)
                {
                    return new ResponseModel
                    {
                        Code = State.请求成功,
                        Message = "修改成功",
                        Count = 1,
                    };
                }
                else
                {
                    return new ResponseModel
                    {
                        Code = State.请求失败,
                        Message = "修改失败",
                        Count = 0,
                    };
                }

            }
            catch (Exception ex)
            {
                //控制台输出
                Console.WriteLine(ex.Message);
                //写入日志
                _logger.LogError(ex.Message);
                throw;
                throw;
            };
        }
        /// <summary>
        /// 修改状态
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        public ResponseModel UserUpdateState(AddUserDto m)
        {
            try
            {
                if (m.State == 0)
                {
                    m.State = 1;
                }
                else
                {
                    m.State = 0;
                }
                var s = _mapper.Map<User>(m);
                _baseUser.Update(s);
                int data = _unitOfWork.SaveChangs();
                if (data > 0)
                {
                    return new ResponseModel
                    {
                        Code = State.请求成功,
                        Message = "修改成功",
                        Count = data,
                    };
                }
                else
                {
                    return new ResponseModel
                    {
                        Code = State.请求失败,
                        Message = "修改失败",
                        Count = data,
                    };
                }

            }
            catch (Exception ex)
            {
                //控制台输出
                Console.WriteLine(ex.Message);
                //写入日志
                _logger.LogError(ex.Message);
                throw;
                throw;
            };
        }
        /// <summary>
        /// 角色显示
        /// </summary>
        /// <returns></returns>
        public dynamic RoleQuery()
        {
            var list = _baseRolers.Query();
            return list;
        }
        /// <summary>
        /// 角色添加
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public ResponseModel AddUserRole(UserRoleDto dto)
        {
            var s = _mapper.Map<UserRole>(dto);
            _baseUserRole.Add(s);
            int data = _unitOfWork.SaveChangs();
            if (data > 0)
            {
                return new ResponseModel
                {
                    Code = State.请求成功,
                    Message = "添加成功",
                    Count = data,
                };
            }
            else
            {
                return new ResponseModel
                {
                    Code = State.请求失败,
                    Message = "添加失败",
                    Count = 0,
                };
            }
        }
        /// <summary>
        /// 用户删除（单删）
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ResponseModel UserDelete(string id)
        {
            try
            {
                var list = _baseUser.Query().FirstOrDefault(x => x.Id.ToString().Equals(id));
                _baseUser.Delete(list.Id);
                int data = _unitOfWork.SaveChangs();
                if (data > 0)
                {
                    return new ResponseModel
                    {
                        Code = State.请求成功,
                        Message = "删除成功",
                        Count = data,
                    };
                }
                else
                {
                    return new ResponseModel
                    {
                        Code = State.请求失败,
                        Message = "删除失败",
                        Count = data,
                    };
                }
            }
            catch (Exception ex)
            {
                //控制台输出
                Console.WriteLine(ex.Message);
                //写入日志
                _logger.LogError(ex.Message);
                throw;
            };
        }
        /// <summary>
        /// 表单删除（批删）
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public ResponseModel AllUserDelete(List<AddUserDto> dto)
        {
            try
            {
                foreach (var item in dto)
                {
                    var list = _baseUser.Query().FirstOrDefault(x => x.Id == item.Id);
                    if (list != null)
                    {
                        _baseUser.Delete(list.Id);
                    }
                    else
                    {
                        return new ResponseModel
                        {
                            Code = State.请求失败,
                            Message = "删除失败",
                        };
                    }
                }
                int data = _unitOfWork.SaveChangs();
                if (data > 0)
                {
                    return new ResponseModel
                    {
                        Code = State.请求成功,
                        Message = "删除成功",
                        Count = data,
                    };
                }
                else
                {
                    return new ResponseModel
                    {
                        Code = State.请求失败,
                        Message = "删除失败",
                        Count = data,
                    };
                }
            }
            catch (Exception ex)
            {
                //控制台输出
                Console.WriteLine(ex.Message);
                //写入日志
                _logger.LogError(ex.Message);
                throw;
            };

        }

        /// <summary>
        /// 获取用户权限
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        //public List<Permission> GetUserPermissions(int userId)
        //{
        //}
    }
}
